<template>
  <div class="contain">
    <el-row>
      <el-col :span="16">
        <h1>
          {{ $store.getters.getDatabaseName }}.{{ $store.getters.getCollectionName }}
        </h1>
      </el-col>
      <el-col :span="4">
        <el-statistic :value="documentsValue" title="文档数"></el-statistic>
      </el-col>
      <el-col :span="4">
        <el-statistic :value="indexesValue" title="索引数"></el-statistic>
      </el-col>
    </el-row>
    <el-row>
      <el-card shadow="never" style="border-radius: 15px;">
        <el-form ref="filterForm" :model="filterForm" label-width="40px" label-position="left" inline>
          <el-row>
            <el-form-item>
              <el-switch v-model="joinCollectionSwitch" active-text="连接集合" inactive-text="条件查询"></el-switch>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button type="success" @click="select">查询</el-button>
              <el-button @click="resetFilterForm">重置</el-button>
            </el-form-item>
          </el-row>
          <template v-if="joinCollectionSwitch">
            <el-row v-for="(collection, index) in filterForm.collections" :key="index">
              <el-form-item label-width="85px">
                <template slot="label">
                  <span class="label-style">原集合字段</span>
                </template>
                <el-input v-model="collection.localField" placeholder="localField"></el-input>
              </el-form-item>
              <el-form-item label-width="70px">
                <template slot="label">
                  <span class="label-style">连接集合</span>
                </template>
                <el-select v-model="filterForm.collections[index].name" placeholder="请选择">
                  <el-option
                      v-for="item in collectionOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="100px">
                <template slot="label">
                  <span class="label-style">连接集合字段</span>
                </template>
                <el-input v-model="collection.foreignField" placeholder="foreignField"></el-input>
              </el-form-item>
              <el-form-item label-width="40px">
                <template slot="label">
                  <span class="label-style">别名</span>
                </template>
                <el-input v-model="collection.as" placeholder="AS"></el-input>
              </el-form-item>
              <el-form-item>
                <el-link style="margin-right: 10px;" icon="el-icon-plus" :underline="false"
                         @click="addCollection"></el-link>
                <el-link v-if="filterForm.collections.length > 1" icon="el-icon-minus" :underline="false"
                         @click="subCollection(index)"></el-link>
              </el-form-item>
            </el-row>
          </template>
          <template v-else>
            <el-row v-for="(field, index) in filterForm.filters" :key="'field' + index">
              <el-form-item label-width="70px">
                <template slot="label">
                  <span style="font-size: 14px;font-weight: bolder;">筛选字段</span>
                </template>
                <el-input v-model="field.key" placeholder="field"></el-input>
              </el-form-item>
              <el-form-item>
                <template slot="label">
                  <span class="label-style">条件</span>
                </template>
                <el-select v-model="field.filter" placeholder="请选择" style="width: 100px;">
                  <el-option
                      v-for="item in filterOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="25px">
                <template slot="label">
                  <span class="label-style">值</span>
                </template>
                <el-input v-model="field.value" placeholder="value"></el-input>
              </el-form-item>
              <el-form-item>
                <template slot="label">
                  <span class="label-style">类型</span>
                </template>
                <el-select v-model="filterForm.filters[index].type" placeholder="请选择" style="width: 150px;">
                  <el-option
                      v-for="item in typeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="70px">
                <template v-if="filterForm.filters.length > 1 && index !== filterForm.filters.length - 1">
                  <template slot="label">
                    <span class="label-style">逻辑类型</span>
                  </template>
                  <el-select v-model="filterForm.filters[index + 1].join" placeholder="请选择" style="width: 100px;">
                    <el-option
                        v-for="item in joinOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </template>
              </el-form-item>
              <el-form-item>
                <el-link style="margin-right: 10px;" icon="el-icon-plus" :underline="false"
                         @click="addFiled"></el-link>
                <el-link v-if="filterForm.filters.length > 1" icon="el-icon-minus" :underline="false"
                         @click="subFiled(index)"></el-link>
              </el-form-item>
            </el-row>
            <el-row v-for="(project, index) in filterForm.projects" :key="'project' + index">
              <el-form-item label-width="70px">
                <template slot="label">
                  <span class="label-style">投影字段</span>
                </template>
                <el-input v-model="project.key" placeholder="field"></el-input>
              </el-form-item>
              <el-form-item>
                <el-radio-group v-model="project.value">
                  <el-radio label="0">排除</el-radio>
                  <el-radio label="1">包含</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-link style="margin-right: 10px;" icon="el-icon-plus" :underline="false"
                         @click="addProjectFiled"></el-link>
                <el-link v-if="filterForm.projects.length > 1" icon="el-icon-minus" :underline="false"
                         @click="subProjectFiled(index)"></el-link>
              </el-form-item>
            </el-row>
            <el-row v-for="(sort, index) in filterForm.sorts" :key="'sort' + index">
              <el-form-item label-width="70px">
                <template slot="label">
                  <span class="label-style">排序字段</span>
                </template>
                <el-input v-model="sort.key" placeholder="field"></el-input>
              </el-form-item>
              <el-form-item>
                <el-radio-group v-model="sort.value">
                  <el-radio label="1">升序</el-radio>
                  <el-radio label="-1">降序</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-link style="margin-right: 10px;" icon="el-icon-plus" :underline="false"
                         @click="addSortFiled"></el-link>
                <el-link v-if="filterForm.sorts.length > 1" icon="el-icon-minus" :underline="false"
                         @click="subSortFiled(index)"></el-link>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <template slot="label">
                  <span class="label-style">跳过</span>
                </template>
                <el-input v-model="filterForm.skip" placeholder="0"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <template slot="label">
                  <span class="label-style">范围</span>
                </template>
                <el-input v-model="filterForm.pageSize" placeholder="10"></el-input>
              </el-form-item>
            </el-row>
          </template>
        </el-form>
        <template v-if="filterTags.length > 0">
          <el-tag :key="index" v-for="(tag, index) in filterTags" style="margin-right: 10px;" closable
                  :disable-transitions="false" @close="handleCloseTag('filter', index)" type="danger">
            {{ tag.key + ' ' + tag.filter + ' ' + tag.value }}
          </el-tag>
        </template>
        <template v-if="collectionTags.length > 0">
          <el-tag :key="index" v-for="(tag, index) in collectionTags" style="margin-right: 10px;" closable
                  :disable-transitions="false" @close="handleCloseTag('collection', index)" type="warning">
            {{ tag.name + ' ' + tag.localField + ' ' + tag.foreignField + ' ' + tag.as }}
          </el-tag>
        </template>
      </el-card>
    </el-row>
    <el-row style="margin: 10px 0;">
      <el-col :span="3">
        <el-dropdown trigger="click" @command="handleAddCommand">
          <el-button type="success">
            <i class="el-icon-download"></i>插入文档<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="json">
              导入JSON文件
            </el-dropdown-item>
            <el-dropdown-item command="document">
              新建文档
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="3">
        <el-button icon="el-icon-upload" @click="exportDocument">导出文档</el-button>
      </el-col>
      <el-col :span="3">
        <el-popconfirm title="确认删除文档吗？" style="margin-left: 10px;" @confirm="dropDocument">
          <el-button slot="reference" type="danger">删除文档</el-button>
        </el-popconfirm>
      </el-col>
      <el-col :span="10" :offset="5">
        {{ page.totalCount }} 条文档,每页 {{ page.size }} 条文档,共 {{ page.totalPage }} 页,当前第 {{ page.currentPage }} 页
        <el-link :underline="false" class="refresh-link" @click="refresh"><i
            class="el-icon-refresh"></i>
        </el-link>
        <el-pagination @prev-click="prev" @next-click="next" class="pagination"
                       layout="prev, next" :page-size="page.size" :total="page.totalPage">
        </el-pagination>
      </el-col>
    </el-row>
    <el-row>
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAllDocuments" @change="handleCheckAllChange">全选</el-checkbox>
      <el-card style="margin-bottom: 10px;" v-for="(document, index) in documentsTree" :key="index" shadow="never">
        <el-row style="margin-bottom: 10px;">
          <el-checkbox v-model="checkDocumentList[index].check" @change="checkButton"></el-checkbox>
          <el-button style="margin-left: 10px;" @click="handleAddCommand('edit', index)">编辑文档</el-button>
          <el-button @click="handleAddCommand('clone', index)">克隆文档</el-button>
          <el-button @click="copyDocument(index)">复制文档</el-button>
        </el-row>
        <el-row>
          <el-tree :data="document" :props="defaultProps">
            <span slot-scope="{node, data}">
              <span style="font-weight: bolder;">{{ node.label }}: </span>
              <span v-if="data.value === 'Object' || data.value === 'Array'"
                    style="font-weight: bolder;">{{ data.value }}</span>
              <span v-else-if="typeof data.value === 'number'" style="color: #2F6CE1">{{ data.value }}</span>
              <span v-else-if="typeof data.value === 'boolean'">{{ data.value }}</span>
              <span v-else>{{ '"' + data.value + '"' }}</span>
            </span>
          </el-tree>
        </el-row>
      </el-card>
    </el-row>

    <!-- 插入和导入document对话框 -->
    <el-dialog :title="documentDialogTitle" :visible.sync="documentDialog" width="40%" :close-on-click-modal="false"
               @closed="closeDocumentDialogDialog">
      <template v-if="documentDialogTitle === '导入文档'">
        <el-form label-position="top" size="small">
          <el-upload action="none" :accept="'.json'" :auto-upload="false" :file-list="importFileList"
                     :limit="1" :on-change="importFileChange" :on-exceed="importExceed">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div class="el-upload__tip" slot="tip">只能上传 json 文件，且不超过 1GB</div>
          </el-upload>
        </el-form>
      </template>
      <template v-else>
        <el-link @click="beautify" style="font-size: 2em;" :underline="false" icon="el-icon-magic-stick"></el-link>
        <b-ace-editor v-model="insertJson" lang="json" width="100%" theme="github" :font-size="13"></b-ace-editor>
      </template>
      <template slot="footer" class="dialog-footer">
        <el-button @click="documentDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitDocument">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {dropDocument, getDocumentsInfo, getDocumentsInfoList, insertDocument, updateDocument} from "@/api/documents";
import FileSaver from 'file-saver'
import {getCollectionsInfoList} from "@/api/collections";

export default {
  name: "Documents",
  data() {
    return {
      documentsValue: null,
      indexesValue: null,
      joinOptions: [
        {label: 'and', value: 'and'},
        {label: 'or', value: 'or'},
      ],
      filterOptions: [
        {label: '==', value: 'eq'},
        {label: '!=', value: 'ne'},
        {label: '>', value: 'gt'},
        {label: '>=', value: 'gte'},
        {label: '<', value: 'lt'},
        {label: '<=', value: 'lte'},
        {label: 'in', value: 'in'},
        {label: 'not in', value: 'nin'},
      ],
      typeOptions: [
        {label: 'Integer', value: '1'},
        {label: 'String', value: '2'},
        {label: 'Boolean', value: '3'},
        {label: 'List', value: '4'},
      ],
      filterForm: {
        filters: [
          {
            key: '',
            filter: '',
            value: '',
            type: '',
            join: ''
          }
        ],
        sorts: [
          {
            key: '',
            value: ''
          }
        ],
        projects: [
          {
            key: '',
            value: ''
          }
        ],
        collections: [
          {
            name: '',
            localField: '',
            foreignField: '',
            as: ''
          }
        ],
        skip: '',
        pageSize: '',
        currentPage: '',
      },
      collectionOptions: [],
      joinCollectionSwitch: false,
      documentsTree: [],
      documents: [],
      isIndeterminate: false,
      checkAllDocuments: false,
      checkDocumentList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      page: {
        size: null,
        totalCount: null,
        totalPage: null,
        currentPage: null,
        prePage: null,
        nextPage: null
      },
      filterTags: [],
      collectionTags: [],
      documentDialog: false,
      documentDialogTitle: '',
      insertJson: '',
      importFileList: []
    }
  },
  watch: {
    "$store.state.collectionName": {
      handler(newVal) {
        this.resetFilterForm()
        this.getDocumentsInfoList(this.$store.getters.getDatabaseName, newVal, this.filterForm)
        this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
      },
      deep: true
    },
    joinCollectionSwitch: {
      handler(newVal) {
        if (newVal) {
          this.filterForm.collections = [
            {
              name: '',
              localField: '',
              foreignField: '',
              as: ''
            }
          ]
          this.collectionOptions = []
          getCollectionsInfoList(this.$store.getters.getDatabaseName).then(res => {
            res.data.forEach(collection => {
              let collectionName = collection.ns.substring(collection.ns.indexOf('.') + 1, collection.ns.length)
              let option = {
                label: collectionName,
                value: collectionName
              }
              this.collectionOptions.push(option)
            })
          })
        }
      }
    }
  },
  created() {
    if (this.$store.getters.getDatabaseName === null) {
      this.$router.push('/databases')
    } else if (this.$store.getters.getCollectionName === null) {
      this.$router.push('/collections')
    } else {
      this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
      this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
    }
  },
  methods: {
    checkButton() {
      this.isIndeterminate = this.checkDocumentList.some(function (item) {
        return item.check
      })
    },
    handleCheckAllChange(val) {
      if (val) {
        this.checkDocumentList.forEach(document => {
          document.check = true
        })
      } else {
        this.checkDocumentList.forEach(document => {
          document.check = false
        })
        this.isIndeterminate = false
      }
    },
    copyDocument(index) {
      navigator.clipboard.writeText(JSON.stringify(this.documents[index], null, 2)).then(() => {
        this.$message.success('Copy成功！')
      })
    },
    dropDocument() {
      let documents = this.checkDocumentList.filter(item => {
        return item.check
      }).map(item => {
        return item.document
      })
      if (documents.length < 1) {
        this.$message.error("请选择文档再进行操作！")
        return
      }
      const loading = this.$loading({
        lock: true,
        text: '删除中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        dropDocument(documents, this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.$store.getters.getConnectionId).then(() => {
          this.$message.success("成功删除文档！")
          this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
          this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
          this.isIndeterminate = false
        }).catch(() => {
          this.$message.error("删除文档失败！")
        })
      }, 1000);
    },
    importExceed() {
      this.$alert('只能上传一个文件！', '上传错误', {
        confirmButtonText: '确认'
      });
    },
    importFileChange(file, fileList) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);

      const whiteList = ["json"];

      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$alert('上传文件只能是 json 格式', '上传错误', {
          confirmButtonText: '确认',
          type: 'error'
        });
        fileList.pop()
        return false;
      }

      const isLt10M = file.size / 1024 / 1024 < 1024;

      if (!isLt10M) {
        this.$alert('上传文件大小不能超过 1GB', '上传错误', {
          confirmButtonText: '确认',
          type: 'error'
        });
        fileList.pop()
        return false;
      }
      const reader = new FileReader();
      reader.readAsText(file.raw)
      reader.onload = (e) => {
        this.insertJson = e.target.result
      }
    },
    submitDocument() {
      try {
        if (JSON.parse(this.insertJson.trim())) {
          let document = JSON.parse(this.insertJson.trim())
          let documents = []
          if (Array.isArray(document)) {
            documents = document
          } else if (document.constructor === Object) {
            documents.push(document)
          }
          const loading = this.$loading({
            lock: true,
            text: this.documentDialogTitle + '中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          setTimeout(() => {
            loading.close();
            var flag = false
            if (this.documentDialogTitle === '编辑文档') {
              // edit
              updateDocument(documents, this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.$store.getters.getConnectionId).then(() => {
                this.$message.success("成功编辑文档！")
                flag = true
              }).catch(() => {
                this.$message.error("编辑文档失败！")
              })
            } else {
              // insert
              insertDocument(documents, this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.$store.getters.getConnectionId).then(() => {
                this.$message.success("成功插入文档！")
                flag = true
              }).catch(() => {
                this.$message.error("插入文档失败！")
              })
            }
            if (flag) {
                this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
                this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
            }
            this.documentDialog = false
          }, 1000);
        }
      } catch (e) {
        this.$message.error("json格式不正确！")
      }
    },
    closeDocumentDialogDialog() {
      this.insertJson = ''
      this.importFileList = []
    },
    beautify() {
      try {
        this.insertJson = JSON.stringify(JSON.parse(this.insertJson), null, 2)
        this.$message.success("成功格式化！")
      } catch (e) {
        this.$message.error("json格式不正确！")
      }
    },
    handleCloseTag(type, index) {
      let form = JSON.parse(JSON.stringify(this.filterForm))
      if (type === 'filter') {
        this.filterTags.splice(index, 1);
        form.filters = this.filterTags
      } else {
        this.collectionTags.splice(index, 1);
        form.collections = this.collectionTags
      }

      this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, form)
    },
    getDocumentsInfo(databaseName, collectionName) {
      getDocumentsInfo(databaseName, collectionName).then(res => {
        this.indexesValue = res.data.indexes
        this.documentsValue = res.data.documents
      })
    },
    getDocumentsInfoList(databaseName, collectionName, filterFrom) {
      let form = {}
      if (filterFrom.currentPage === '' || filterFrom.currentPage === null || filterFrom.currentPage === undefined) {
        form.currentPage = 1
      } else {
        form.currentPage = filterFrom.currentPage
      }
      if (filterFrom.pageSize === '' || filterFrom.pageSize === null || filterFrom.pageSize === undefined) {
        form.pageSize = 10
      } else {
        form.pageSize = filterFrom.pageSize
      }
      if (filterFrom.skip === '' || filterFrom.skip === null || filterFrom.skip === undefined) {
        form.skip = 0
      } else {
        form.skip = filterFrom.skip
      }
      if (filterFrom.sorts.length === 0 || filterFrom.sorts[0].key === '' || filterFrom.sorts[0].value === '') {
        form.sorts = []
      } else {
        form.sorts = filterFrom.sorts
      }
      if (filterFrom.projects.length === 0 || filterFrom.projects[0].key === '' || filterFrom.projects[0].value === '') {
        form.projects = []
      } else {
        form.projects = filterFrom.projects
      }
      if (filterFrom.filters.length === 0 || filterFrom.filters[0].key === '') {
        form.filters = []
      } else {
        form.filters = filterFrom.filters
        filterFrom.filters[0].join = 'and'
      }
      if (filterFrom.collections.length === 0 || filterFrom.collections[0].name === '') {
        form.collections = []
      } else {
        form.collections = filterFrom.collections
      }
      getDocumentsInfoList(databaseName, collectionName, form).then(res => {
        let documents = [];
        this.page.size = res.data.pageSize
        this.page.totalCount = res.data.documentCount
        this.page.totalPage = res.data.totalPage
        this.page.currentPage = res.data.currentPageNo
        this.page.prePage = res.data.prePage
        this.page.nextPage = res.data.nextPage
        this.checkDocumentList = []
        res.data.documents.forEach(doc => {
          let document = this.builder(doc)
          documents.push(document)
          let checkDocument = {
            document: doc,
            check: false
          }
          this.checkDocumentList.push(checkDocument)
        })
        this.documentsTree = documents
        this.documents = res.data.documents
        this.filterTags = JSON.parse(JSON.stringify(form.filters))
        this.collectionTags = JSON.parse(JSON.stringify(form.collections))
        this.isIndeterminate = false
        this.checkAllDocuments = false
      })
    },
    builder(doc) {
      let document = []
      Object.keys(doc).forEach(key => {
        let item = {}
        let label
        let value
        let children = null
        if (doc[key] == null) {
          label = key
          value = 'null'
        } else if (Array.isArray(doc[key])) {
          label = key
          value = 'Array'
          children = this.builder(doc[key])
        } else if (doc[key].constructor === Object) {
          label = key
          value = 'Object'
          children = this.builder(doc[key])
        } else {
          label = key
          value = doc[key]
        }
        item.label = label
        item.value = value
        if (children != null) {
          item.children = children
        }
        document.push(item);
      })
      return document
    },
    select() {
      const loading = this.$loading({
        lock: true,
        text: '查询中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
        this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
      }, 1000);
    },
    refresh() {
      const loading = this.$loading({
        lock: true,
        text: '刷新中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
        this.getDocumentsInfo(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName)
      }, 1000);
    },
    addFiled() {
      this.filterForm.filters.push({})
    },
    subFiled(index) {
      this.filterForm.filters.splice(index, 1)
    },
    addSortFiled() {
      this.filterForm.sorts.push({})
    },
    subSortFiled(index) {
      this.filterForm.sorts.splice(index, 1)
    },
    addProjectFiled() {
      this.filterForm.projects.push({})
    },
    subProjectFiled(index) {
      this.filterForm.projects.splice(index, 1)
    },
    addCollection() {
      this.filterForm.collections.push({})
    },
    subCollection(index) {
      this.filterForm.collections.splice(index, 1)
    },
    resetFilterForm() {
      this.filterForm = {
        filters: [
          {
            key: '',
            filter: '',
            value: '',
            type: '',
            join: ''
          }
        ],
        sorts: [
          {
            key: '',
            value: ''
          }
        ],
        projects: [
          {
            key: '',
            value: ''
          }
        ],
        collections: [
          {
            name: '',
            localField: '',
            foreignField: '',
            as: ''
          }
        ],
        skip: '',
        pageSize: '',
        currentPage: '',
      }
    },
    prev() {
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        this.filterForm.currentPage = this.page.prePage
        this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
      }, 1000);
    },
    next() {
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        this.filterForm.currentPage = this.page.nextPage
        this.getDocumentsInfoList(this.$store.getters.getDatabaseName, this.$store.getters.getCollectionName, this.filterForm)
      }, 1000);
    },
    handleAddCommand(command, index) {
      this.documentDialog = true
      if (command === 'json') {
        this.documentDialogTitle = '导入文档'
      } else if (command === 'document') {
        this.documentDialogTitle = '插入文档'
      } else if (command === 'edit') {
        this.documentDialogTitle = '编辑文档'
        this.insertJson = JSON.stringify(this.documents[index], null, 2)
      } else if (command === 'clone') {
        this.documentDialogTitle = '插入文档'
        this.insertJson = JSON.stringify(this.documents[index], null, 2)
      }
    },
    exportDocument() {
      let documents = this.checkDocumentList.filter(item => {
        return item.check
      }).map(item => {
        return item.document
      })
      if (documents.length < 1) {
        this.$message.error("导出文档为空！")
        return
      }
      const data = JSON.stringify(documents, null, 2);
      const blob = new Blob([data], {type: 'application/json'});
      const loading = this.$loading({
        lock: true,
        text: '导出中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      setTimeout(() => {
        loading.close();
        FileSaver.saveAs(blob, 'documents.json')
        this.exportConnectionDialog = false
      }, 1000);
    }
  }
}
</script>

<style scoped>
.contain {
  padding: 20px;
}

.label-style {
  font-size: 14px;
  font-weight: bolder;
}

.refresh-link {
  margin: 0 10px;
  font-size: 1.5em;
}

.pagination {
  display: inline-block;
  font-size: 19px;
}
</style>